package com.mao.disruptor.producer;

import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.mao.disruptor.consumer.LongEventHandler;
import com.mao.disruptor.consumer.LongEventHandler2;
import com.mao.disruptor.entity.LongEvent;
import com.mao.disruptor.factory.LongEventFactory;

import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        // 1.创建一个可缓存的线程池，提供发给 consumer
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 2. 创建一个工厂
        EventFactory<LongEvent> eventFactory = new LongEventFactory();
        // 3. 创建一个 ringBuffer 大小,2的N次方
        int ringBuffer = 1024 * 1024;
        // 4. 创建Disruptor
        Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(eventFactory, ringBuffer, executorService, ProducerType.MULTI, new YieldingWaitStrategy());
        // 5. 连接消费者---注册消费者
        disruptor.handleEventsWith(new LongEventHandler());
        disruptor.handleEventsWith(new LongEventHandler2());
        // 6. 启动
        disruptor.start();
        // 7. 创建 ringBuffer 容器
        RingBuffer<LongEvent> ringBuffers = disruptor.getRingBuffer();
        // 8. 创建生产者
        LongEventProducer producer = new LongEventProducer(ringBuffers);
        // 9. 指定缓冲区的大小
        ByteBuffer buffer = ByteBuffer.allocate(8);
        for (int i = 0; i < 100; i++) {
            buffer.putLong(0, i);
            producer.onData(buffer);
        }
        // 10. 关闭disruptor和executor
        executorService.shutdown();
        disruptor.shutdown();
    }
}
